<template>
  <!-- 推送配置-->
  <div class="">
    <el-dialog :title="title" :visible.sync="visibleDialog" @close="cancel" width="1000px" append-to-body>
      <el-form class="new_form_box" v-loading="loading" ref="form" :model="form" :rules="rules" label-width="80px">
        <div style="margin-bottom: 10px;">
          <formSubTitVue title="渠道设置"></formSubTitVue>
        </div>
        <el-form-item label="接口：" prop="type">
          <div >{{rowData&&rowData.name}}</div>
        </el-form-item>
        <!-- <el-form-item label="启用：" prop="">
          <el-switch v-model="form.state" active-value="0" inactive-value="1"></el-switch>
        </el-form-item> -->
        <el-form-item label="状态:" prop="state" >
          <el-radio-group v-model="form.state">
            <el-radio label="0">启用</el-radio>
            <el-radio label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品类型" prop="ifself" >
          <div>
            <el-radio-group v-model="form.ifself">
              <el-radio :label="3">全部</el-radio>
              <el-radio :label="1">自营</el-radio>
              <el-radio :label="2">代售</el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item label="真假账号:" prop="zhenjiaAccount" >
          <el-radio-group v-model="form.zhenjiaAccount">
            <el-radio :label="1">原账号</el-radio>
            <el-radio :label="2">假账号</el-radio>
            <el-radio :label="3">账号少一位</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="官方代售:" prop="consignment" >
          <el-radio-group style="width: 200px;" v-model="form.consignment">
            <el-radio :label="1">推送</el-radio>
            <el-radio :label="2">不推送</el-radio>
          </el-radio-group>
          <span style="color: #999;margin-left: 25px;" >设置用户在官方代售模块发布的商品是否推送。</span>
        </el-form-item>
        <el-form-item label="供货人:" prop="gonghuoId" >
          <!-- <el-select filterable clearable multiple collapse-tags v-model="form.gonghuoIdArr" placeholder="请选择供货人" >
            <el-option v-for="(item ,key) in yuangongList" :key="key" :label="item.nickName" :value="item.userId" />
          </el-select> -->
          <el-button type="primary" size="mini" @click="setSupplyer('qudao')">设置供货人</el-button>
          <span style="color: #999;margin-left: 25px;" >设置该渠道需要推送的供货人，不设置则默认全部供货人。</span>
        </el-form-item>
        <div>
          <el-form-item label="通道：" prop="type">
            <el-input :disabled="!checkPermi(['push:partner:type:edit'])" style="width:200px" size="small" v-model="form.type" placeholder="请输入通道" />
            <span style="color: #999;margin-left: 25px;" v-if="tongdaoshuomingObj[form.type]">通道说明： 预计【{{ tongdaoshuomingObj[form.type] }}】，如果当前推送任务过多，可能会延迟执行，请耐心等待。</span>
          </el-form-item>
        </div>
        <div style="margin: 10px 0;">
          <formSubTitVue title="游戏设置"></formSubTitVue>
        </div>
        <el-form-item label-width="0px" label="" prop="games">
          <el-table
          border
            ref="multipleTable"
            :data="gameListSeleltOptions"
            tooltip-effect="dark"
            @selection-change="handleSelectionChangeGame"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column label="游戏名称" prop="name" width="150"></el-table-column>
            <el-table-column prop="superName" label="供货人"> 
              <template slot-scope="scope">
                <span v-if="scope.row.superName">{{ scope.row.superName }}</span>
                <div style="color: #999;" v-else>该游戏需要推送的供货人，不设置则使用渠道设置的供货人。</div>
              </template>
            </el-table-column>
            <el-table-column prop="cot" label="操作" width="240"> 
              <template slot-scope="scope">
                <div>
                  <el-button type="primary" size="mini" @click="setSupplyer(scope.row)">设置供货人</el-button>
                  <el-button type="primary" size="mini" @click="openFilterConfig(scope.row)">设置条件</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
        
      </div>
    </el-dialog>
    
    <selectSupplyers ref="selectSupplyers" @change="supplyerChange"></selectSupplyers>
    <moreSetting ref="moreSetting" @change="gameAttrChange"/>
  </div>
</template>

<script>
import {
  getPushByConfigId,
  updatePush,
  pushNewadd
} from "@/api/info/push";
import gameListApi from "@/api/gameConfig/gameList";
import selectSupplyers from './selectSupplyers.vue'
import interfaceChannelApi from "@/api/interfaceChannel/index"
import moreSetting from "./moreSetting.vue"
import supplyConfigApi from "@/api/system/supplyConfig";
export default {
  name: "PushConfig",
  components: { selectSupplyers ,moreSetting},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      visibleDialog: false,
      // 表单参数
      form: {
        id: null,
        createId: null,
        updateId: null,
        createTime: null,
        updateTime: null,
        superId: null,
        games: null,
        config: null,
        exids: null,
        state:'0',
        ifself:3,
        type:'',
        zhenjiaAccount:1,
        consignment:1,//1推送 2不推送
        gonghuoIdArr:[],
        gonghuoId:''
      },
      // 表单校验
      rules: {},
      gameList: [],
      gameListSeleltOptions:[],//可供选择的游戏列表
      selectedGames:[],//已选择的游戏
      isEdit:false,
      rowData:'',
      tongdaoshuomingObj:{},
      yuangongList:[],//所有员工
    };
  },
  created() {
    this.getGameList();
    this.getYuangongList()
  },
  methods: {
    async open(row){
      this.title = "推送配置";
      this.visibleDialog = true;
      this.loading = true
      this.rowData = row
      // this.reset();
      let pushConfig = await this.getConfigList(row.id)
      if(pushConfig){
        // 编辑
        this.isEdit = true
        pushConfig.config = Number(pushConfig.config)
        this.form = {...pushConfig};
        // if(this.form.gonghuoId){
        //   this.form.gonghuoIdArr = JSON.parse(JSON.stringify(this.form.gonghuoId.split(',')))
        // }
        // 获取可选择的游戏列表
        await this.getInterfaceChannel(row.interfaceUserId)
        this.loading = false
        this.$nextTick(()=>{
          setTimeout(()=>{
            this.toggleSelection(this.form.interfacePushes)
          },100)
        })
      }else{
        // 新增
        this.isEdit = false
        this.form.config = row.id
        this.form.state = "0"
        this.form.type = ''
        this.form.ifself = 3
        this.form.zhenjiaAccount = 1
        // 获取可选择的游戏列表
        await this.getInterfaceChannel(row.interfaceUserId,'add')
        this.loading = false
        this.$nextTick(()=>{
          this.toggleSelection()
        })
      }
      this.getTongdao()
    },
       // 获取所有员工列表
    getYuangongList() {
      supplyConfigApi
        .getAllUserList({
          userNewType: 1,
        })
        .then((res) => {
          if(res.rows&&res.rows.length){
            res.rows.forEach(r=>{
              r.userId = String(r.userId)
            })
          }
          this.yuangongList = res.rows;
         
        });
    },

    // 获取通道说明 字典
    getTongdao() {
      this.getDicts("tongdaoshuoming").then((r) => {
        if (r.data && r.data.length) {
          const obj = this.arrayToObject(r.data, "dictLabel");
          if (obj.tongdaoshuoming) {
            try {
              this.tongdaoshuomingObj = JSON.parse(
                obj.tongdaoshuoming.remark
              ).selectPush;
            } catch (error) {}
          }
        }
      });
    },

    // 改变接口启用状态
    customChangeState(){
      let obj = {
        id:this.form.id,

      }
      updateStateByConfigId().then(res=>{

      })
    },
    // 获取该接口渠道下的游戏
    async getInterfaceChannel(interfaceUserId,flag){
      this.gameListSeleltOptions = []
      // 获取该接口渠道下的游戏
      let {data} = await interfaceChannelApi.getInterfaceChannel(interfaceUserId)
      if(this.gameList&&this.gameList.length&&data.gameIds){
        let idArr = data.gameIds.split(',')
        this.gameList.forEach(r=>{
          if(idArr.find(r2=>r2==r.id)){
            this.gameListSeleltOptions.push(JSON.parse(JSON.stringify(r)))
          }
        })
      }
      if(flag=='add'){
        this.form.type = data.type
      }
    },
    // 查询推送配置
    async getConfigList(id) {
      this.loading = true;
      let res = await getPushByConfigId({
        config:id
      })
      this.loading = false;
        if(res.data){
          // 正常 有数据
          return res.data
        }else {
          // 正常 无数据
          return false
        }
    },
    // 选择表格中的游戏
    handleSelectionChangeGame(e){
      this.selectedGames = e;
    },
    
   
    // 选择供货人完成
    supplyerChange(e){
      if(e.gameId=='qudao'){
        // 渠道供货人
        if(e&&e.selectedSupplyList){
          let arr = JSON.parse(e.selectedSupplyList)
          let ids = []
          let names = []
          arr.forEach(sup=>{
            ids.push(sup.create_id)
            names.push(sup.nick_name)
          })
          this.$set(this.form,'gonghuoId',ids.join(','))
          this.$set(this.form,'gonghuoName',names.join(','))
        }else{
          this.$set(this.form,'gonghuoId','')
          this.$set(this.form,'gonghuoName','')
        }
      }else{
        // 游戏选择供货人
        this.gameListSeleltOptions.forEach(r=>{
          if(r.id==e.gameId){
            if(e&&e.selectedSupplyList){
              let arr = JSON.parse(e.selectedSupplyList)
              let ids = []
              let names = []
              arr.forEach(sup=>{
                ids.push(sup.create_id)
                names.push(sup.nick_name)
              })
              this.$set(r,'superId',ids.join(','))
              this.$set(r,'superName',names.join(','))
            }else{
              this.$set(r,'superId','')
              this.$set(r,'superName','')
            }
          }
        })
      }
        
    },

    // // 配置游戏属性完成
    gameAttrChange(e){
      if(e&&e.content){
        this.gameListSeleltOptions.forEach(r=>{
          if(r.id==e.gameId){
            this.$set(r,'content',e.content)
          }
        })
      }else{
        this.$set(r,'content','')
      }
    },



    // 取消按钮
    cancel() {
      this.visibleDialog = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createId: null,
        updateId: null,
        createTime: null,
        updateTime: null,
        superId: null,
        games: null,
        config: null,
        exids: null,
        state:'0',
        ifself:3,
        type:'',
        zhenjiaAccount:1,
        consignment:1,//1推送 2不推送
        gonghuoIdArr:[],
        gonghuoId:''
      };

      this.gameListSeleltOptions = []
      this.selectedGames = []
      this.$nextTick(()=>{
        this.resetForm("form");
      })
    },
    // 游戏列表
    getGameList() {
      gameListApi.getGameList().then((res) => {
        res.rows.forEach(r=>{
          r.id = String(r.id)
        })
        this.gameList = res.rows;
      });
    },
    
    // 回显表格游戏勾选
    toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.gameListSeleltOptions.forEach(r=>{
              if(r.id==row.gameId){
                this.$set(r,'gameId',r.id)
                this.$set(r,'gameName',r.name)
                this.$set(r,'superId',row.superId)
                this.$set(r,'superName',row.superName)
                this.$set(r,'content',row.content)
                this.$set(r,'state',row.state)
                this.$refs.multipleTable.toggleRowSelection(r);
              }
            })
          });
        } else {
         if(this.$refs.multipleTable) this.$refs.multipleTable.clearSelection();
        }
      },
    // 供货人设置
    setSupplyer(row){
      if(row=='qudao'){
        // 渠道级选择员工
        this.$refs.selectSupplyers.open('qudao',this.form.gonghuoId||'',null,this.rowData.tenantId)
      }else{
        // 对应游戏选择员工
        this.$refs.selectSupplyers.open(row.id,row.superId||'',row.content,this.rowData.tenantId)
      }
      
    },

    // 游戏属性设置
    openFilterConfig(item){
      this.$refs.moreSetting.open(item.id,item.content)
    },
    /** 提交按钮 */
    submitForm() {
      // 处理表单数据
      this.form.interfacePushes = []
      if(this.selectedGames&&this.selectedGames.length){
          let ids = []
          let names = []
          let noSup = false
          this.selectedGames.forEach(r=>{
            // if(!r.superId){
            //   noSup = true
            // }
            ids.push(r.id)
            names.push(r.name)
            this.form.interfacePushes.push(
              {
                gameId:r.id,
                gameName:r.name,
                superId:r.superId,
                superName:r.superName,
                content:r.content||'',
                state:'1'
              }
            )
          })
          if(noSup){
            return this.$alert('请给每个游戏选择供货人！')
          }
          this.form.gameIds = ids.join(',')
          this.form.games = names.join(',')
      }else{
        return this.$alert('请选择游戏！')
      }


      this.$refs["form"].validate((valid) => {
        if (valid) {
          // if(this.form.gonghuoIdArr&&this.form.gonghuoIdArr.length){
          //   this.form.gonghuoId = this.form.gonghuoIdArr.join(',')
          // }else{
          //   this.form.gonghuoId = ''
          // }
          if (this.form.id != null) {
            updatePush(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.visibleDialog = false;
            });
          } 
          else {
            this.form.tenantId = this.rowData.tenantId
            pushNewadd(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.visibleDialog = false;
            });
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-radio {
  margin-bottom: 10px !important;
  margin-top: 10px !important;
}
</style>
